import jwt from 'jsonwebtoken'
import { User } from '../models/User'

interface DecodedToken {
  userId: string
}

export const verifyToken = async (token: string) => {
  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET!) as DecodedToken
    const user = await User.findById(decoded.userId)

    if (!user) {
      throw new Error('User not found')
    }

    return {
      id: user._id,
      username: user.username,
      role: user.role,
    }
  } catch (error) {
    throw new Error('Invalid token')
  }
}
